package com.test.io.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

public class TimeClientHandler extends ChannelHandlerAdapter {
	
	private final ByteBuf firstMessage;
	
	public TimeClientHandler(){
		byte[] req="query time".getBytes();
		this.firstMessage=Unpooled.buffer(req.length);
		firstMessage.writeBytes(req);
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		ctx.writeAndFlush(firstMessage);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		// TODO Auto-generated method stub
		System.out.println("unexpected exception from downstream:"+cause.getMessage());
		ctx.close();
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		// TODO Auto-generated method stub
		ByteBuf buf=(ByteBuf)msg;
		byte[] bytes=new byte[buf.readableBytes()];
		buf.readBytes(bytes);
		String body=new String(bytes, "UTF-8");
		System.out.println("NOW TIME IS :"+body);
	}
	
	
	

}
